package gods.bubble.parser;

/*
 * PDFTextParser.java
 *
 * Created on January 24, 2009, 11:55 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author prasanna
 */

//Lucene Field Name	Description
//path	File system path if loaded from a file
//url	URL to PDF document
//contents	Entire contents of PDF document, indexed but not stored
//summary	First 500 characters of content
//modified	The modified date/time according to the url or path
//uid	A unique identifier for the Lucene document.
//CreationDate	From PDF meta-data if available
//Creator	From PDF meta-data if available
//Keywords	From PDF meta-data if available
//ModificationDate	From PDF meta-data if available
//Producer	From PDF meta-data if available
//Subject	From PDF meta-data if available
//Trapped	From PDF meta-data if available

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.searchengine.lucene.LucenePDFDocument;
import org.apache.pdfbox.util.PDFTextStripper;

public class PDFTextParser {
	// Get Lucene Document from PDF Document
	public static Document parsePDF(File file, String url) throws IOException {
		Document document = null;

		document = LucenePDFDocument.getDocument(file);

		return document;
	}

	// Extract text from PDF Document
	public static String pdftoText(File file) {
		PDFParser parser = null;
		String parsedText = null;
		PDFTextStripper pdfStripper = null;
		PDDocument pdDoc = null;
		COSDocument cosDoc = null;

		if (!file.isFile()) {
			System.out.println("File " + file.getName() + " does not exist.");
			return null;
		}

		try {
			parser = new PDFParser(new FileInputStream(file));
		} catch (Exception e) {
			System.out.println("Unable to open PDF Parser.");
			return null;
		}

		try {
			parser.parse();
			cosDoc = parser.getDocument();
			pdfStripper = new PDFTextStripper();
			pdDoc = new PDDocument(cosDoc);
			parsedText = pdfStripper.getText(pdDoc);
		} catch (Exception e) {
			System.out.println("Failed in parsing " + file.getAbsolutePath());

			try {
				if (cosDoc != null)
					cosDoc.close();
				if (pdDoc != null)
					pdDoc.close();
			} catch (Exception e1) {

			}

			return null;
		} finally {
			try {
				cosDoc.close();
			} catch (Exception e) {
			}
		}

		return parsedText;
	}
}